package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Semester;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import dao.SemesterDAO;

/**
 * Servlet implementation class SemesterData
 */
public class SemesterData extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public SemesterData() {
		super();
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		response.setHeader("Cache-Control", "no-cache");
		try {
			List<Semester> semesters = SemesterDAO.get();
			PrintWriter outWriter = response.getWriter();
			JSONObject semestersList = new JSONObject();
			JSONArray jsonList = new JSONArray();

			for (Semester semester : semesters) {
				JSONObject jsonSemester = new JSONObject();
				jsonSemester.put("key", semester.getId());
				jsonSemester.put("nameValue", semester.getText());
				jsonList.add(jsonSemester);
			}
			semestersList.put("semesters", jsonList);
			outWriter.write(semestersList.toString());
		} catch (Throwable theException) {
			System.out.println(theException);
		}
	}

}
